import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Button, Form, Row, Col, Icon, DatePicker, Modal, Spin } from 'antd';
import {
  WeaTop,
  WeaTab,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaSearchGroup,
  WeaRightMenu,
  WeaPopoverHrm,
  WeaDialog,
  WeaTools,
  WeaFormItem,
  WeaDatePicker,
  WeaNewScroll,
  WeaErrorPage
} from 'ecCom';
import { WeaSwitch, WeaTableNew } from 'comsMobx'
const { WeaTable } = WeaTableNew;

import MeetingDialog from '../../public/dialog/index';
import RoomPlanDialog from '../../public/roomPlan/index';
import EndRepeatMeeting from './EndRepeatMeeting'
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

const store = ['meetingRepeat','meetingDialog','meetingStoreMap']
@inject(...store)
@observer
class Repeat extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      RoomPlanContainer: false,
      dialogType: 'preview',
      meetingId: '',
      visible: false,
    }
  }

  componentDidMount() {
    this.props.meetingRepeat.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.props.meetingRepeat.doInit();
    }
  }

  componentWillUnmount() {
    //组件卸载时一般清理一些状态
  }

  doRefesh = () => {
    this.props.meetingRepeat.getRepeatDatas();
  }
  
  setAll = (meetingId, bool, type) => {
    this.setState({
      meetingId: meetingId,
      visible: bool,
      dialogType: type
    })
  }
  setMeetingId = (meetingId) => {
    this.setState({ meetingId: meetingId })
  }
  setRoomPlan = (bool) => {
    this.setState({ RoomPlanContainer: bool })
  }
  setDialog = (bool) => {
    this.setState({ visible: bool })
  }
  setType = (type) => {
    this.setState({ dialogType: type })
  }

  //标签页切换时触发
  changeData = (v) => {
    const { meetingRepeat } = this.props;
    meetingRepeat.setState({showSearchAd: false});
    meetingRepeat.timeSag = v;
    meetingRepeat.form.updateFields({
      timeSag__meetingStartdatefrom__meetingStartdateto: {
        value: v
      }
    });
    meetingRepeat.getRepeatDatas();
  }

  getRightMenu = () => {
    const {meetingRepeat} = this.props;
    const selectedRowKeys = toJS(meetingRepeat.comsWeaTableStore.selectedRowKeys) || [];
    let btnArr = [
      {
        key: 'BTN_ADD',
        icon: <i className='icon-coms-New-Flow'/>,
        content : `${getLabel(126105,'新建')}`,
        onClick : () => this.onRightMenuClick('BTN_ADD')
      },
      {
        key: 'BTN_DEL',
        icon: <i className='icon-coms-delete'/>,
        content : `${getLabel(32136,'批量删除')}`,
        disabled: selectedRowKeys.length == 0,
        onClick : () => this.onRightMenuClick('BTN_DEL')
      },
      {
        key: 'BTN_COLUMN',
        icon: <i className='icon-coms-Custom'/>,
        content : `${getLabel(32535,'显示列定制')}`,
        onClick : () => this.onRightMenuClick('BTN_COLUMN')
      }
    ]
    return btnArr
  }

  onRightMenuClick = (type) => {
    const { meetingRepeat, meetingDialog } = this.props;
    const { comsWeaTableStore} = meetingRepeat;
    const selectedRowKeys = toJS(comsWeaTableStore.selectedRowKeys) || [];
    if (type == 'BTN_ADD') {
      this.setAll('', true, 'create');
      meetingDialog.setState({ meeetingDateVisible: false });
    }
    if (type == 'BTN_DEL') {
      Modal.confirm({
        content: `${getLabel(383453,"确定要删除已选择的会议吗")}?`,
        onOk() {
          meetingRepeat.DeleteIntvl({ meetingid: selectedRowKeys });
        }
      });
    }
    if(type=='BTN_COLUMN'){
      comsWeaTableStore.setColSetVisible(true);
      comsWeaTableStore.tableColSet(true);
    }
  }

  getButtons = () => {
    const selectedRowKeys = toJS(this.props.meetingRepeat.comsWeaTableStore.selectedRowKeys) || [];
    let btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x9x423@BTN_ADD`} type="primary" onClick={() => {this.onRightMenuClick('BTN_ADD')}}>{getLabel(83981,"新建")}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fois0j@BTN_DEL`} type="primary" disabled={selectedRowKeys.length == 0} onClick={() => {this.onRightMenuClick('BTN_DEL')}}>{getLabel(32136,'批量删除')}</Button>
    ];
    return btns
  }

  //高级搜索底部按钮定义
  getTabButtonsAd = () => {
    const { meetingRepeat } = this.props;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rfwrb0@doSearch`} type="primary" onClick={() => {
        this.changeTabKey();
        meetingRepeat.getRepeatDatas();
        meetingRepeat.setState({showSearchAd: false});
      }}>{getLabel(197,"搜索")}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oard28@doReset`} type="ghost" onClick={() => {
        meetingRepeat.form.reset()
      }}>{getLabel(2022,"重置")}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6wv11j@doCancel`} type="ghost" onClick={() => {
        meetingRepeat.setState({showSearchAd: false});
      }}>{getLabel(201,"取消")}</Button>)
    ]
  }

  //高级搜索group定义
  getSearchs = () => {
    const { meetingRepeat } = this.props;
    const { form } = meetingRepeat;
    const conditioninfo = meetingRepeat.conditioninfo;
    const { isFormInit } = form;
    let group = [];
    isFormInit && conditioninfo.map((c,index) => {
      let items = [];
      c.items.map(fields => {
        if (fields.isQuickSearch) {
          this.quickSearchPara = fields.domkey[0];
        }
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@semk9r@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@c13bed@${fields.domkey[0]}`} fieldConfig={fields} form={form} onChange={null/*todo*/} onEnterSearch={this.onEnterSearch}/>
          </WeaFormItem>),
          colSpan: 1
        })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@aa0sft@${index}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
    });
    return group;
  }

  onEnterSearch = ()=>{
    const { meetingRepeat } = this.props;
    this.changeTabKey();
    meetingRepeat.getRepeatDatas();
    meetingRepeat.setState({showSearchAd: false});
  }

  //列表后操作菜单
  getOperatesClick = (record, index, operate, flag) => {
    const { meetingRepeat } = this.props;
    let meetingid = record.id;
    let operateType = operate.index;//根据后台接口操作按钮显示顺序确定操作类型 0停止 1提前结束 2取消
    if (operateType == 0) {//0停止
      Modal.confirm({
        content: `${getLabel(386204, '确定要停止该周期会议吗')}`,
        onOk() {meetingRepeat.StopIntvl({ meetingid: meetingid })}
      });
    }
    if (operateType == 1) {//1提前结束
      this.refs.MeetingDialog &&
      meetingRepeat.setState({
        repeatenddate: record.repeatenddate,
        enddate: record.repeatenddate,
        repeatbegindate: record.repeatbegindate
      });

      const endRepeatStore  = this.props.meetingStoreMap.getMapStore(1);
      endRepeatStore.advanceModal(true, {
        meetingid: record.id,
        repeatenddate: record.repeatenddate,
      });
    }
    if (operateType == 2) {//2取消
      Modal.confirm({
        content: `${getLabel(383340,"确定要取消该周期会议吗")}?`,
        onOk() {
          meetingRepeat.CancelIntvl({ meetingid });
          meetingRepeat.getRepeatDatas(false);
        }
      });
    }
    if(operateType == 3) { // 删除
      Modal.confirm({
        content: `${getLabel(383453,"确定要删除已选择的会议吗")}?`,
        onOk() {
          meetingRepeat.DeleteIntvl({ meetingid: meetingid});
        }
      });
    }

  }

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        return (
          newColumn.dataIndex == 'name' ?
            <a onClick={() => {
              this.setState({meetingId: record.id, visible: true,dialogType: 'preview'})
            }} dangerouslySetInnerHTML={{ __html: valueSpan }} />
            :
            <div dangerouslySetInnerHTML={{ __html: valueSpan }} />
        )
      }
      return newColumn;
    });
    return newColumns;
  }

  changeTabKey = () => {
    const {meetingRepeat} = this.props;
    const params = meetingRepeat.form.getFormParams() || {};
    if(params.timeSag && params.timeSag !== meetingRepeat.timeSag){
      meetingRepeat.setState({timeSag: params.timeSag});
    }
  }

  render() {
    let { RoomPlanContainer, visible, dialogType, meetingId  } = this.state;

    const {meetingRepeat} = this.props;
    const {
      getRepeatDatas, comsWeaTableStore, form,
      title, topTab, loading, showSearchAd, timeSag, createDate
    } = meetingRepeat;

    let collectParams={
      favname: title,
      favouritetype: 5,
      objid: 0,
      importantlevel: 1,
    };

    return (
      <div className="metting-repeat">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@qzk1a2`} datas={this.getRightMenu()} collectParams={collectParams}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@9u0ptj`}
            title={title}
            loading={loading}
            icon={<i className='icon-coms-meeting' />}
            iconBgcolor='#f14a2d'
            buttons={this.getButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={{
              datas: this.getRightMenu(),
              collectParams: collectParams
            }}
          >
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@0z2h23`}
              keyParam="viewcondition"
              countParam="groupid"
              datas={topTab}
              buttonsAd={this.getTabButtonsAd()}
              searchsBaseValue={form.getFormParams()[this.quickSearchPara] || ''}
              searchType={['base', 'advanced']}
              setShowSearchAd={bool => meetingRepeat.setState({showSearchAd: bool})}
              hideSearchAd={() =>meetingRepeat.setState({showSearchAd: false})}
              searchsAd={<Form ecId={`${this && this.props && this.props.ecId || ''}_Form@ngpkps`} horizontal>{this.getSearchs()}</Form>}
              showSearchAd={showSearchAd}
              onSearch={() => {getRepeatDatas();}}
              selectedKey={timeSag}
              onSearchChange={value => {
                form.updateFields({
                  names: {
                    value: value
                  },
                })
              }}
              onChange={(v) => this.changeData(v)}
            />
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@1fygvp`}
              comsWeaTableStore={comsWeaTableStore}
              hasOrder={true}
              needScroll={true}
              onOperatesClick={this.getOperatesClick}
              getColumns={this.getColumns}
            />
          </WeaTop>
        </WeaRightMenu>

        <MeetingDialog ecId={`${this && this.props && this.props.ecId || ''}_MeetingDialog@5peoyc`}
          setRoomPlan={this.setRoomPlan}
          setDialog={this.setDialog}
          setType={this.setType}
          setMeetingId={this.setMeetingId}
          setAll={this.setAll}
          ref='MeetingDialog'
          type={dialogType}//新建为'create',查看为'preview',编辑edit,会议决议---待定
          visible={visible}//显隐受控
          doRefesh={this.doRefesh}//自定义刷新页面，不会关掉弹出框
          meetingId={meetingId} //会议id，查看会议时用到
          isInterval={true}//新建会议类型，true是周期会议， false是普通会议
          meetingDate={createDate}//新建日期
        />
        {RoomPlanContainer && <RoomPlanDialog ecId={`${this && this.props && this.props.ecId || ''}_RoomPlanDialog@u92pq3`}
          setRoomPlan={this.setRoomPlan}
          setDialog={this.setDialog}
          setType={this.setType}
          setMeetingId={this.setMeetingId}
          canCreate={false}
          height={600}
          visible={RoomPlanContainer} />}
        <EndRepeatMeeting ecId={`${this && this.props && this.props.ecId || ''}_EndRepeatMeeting@2vesqr`} storeKey={1} setAll = {this.setAll} doRefesh = {this.doRefesh}/>
      </div>
    )
  }
}

//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@jdfipo`} msg={hasErrorMsg ? this.props.error : getLabel(383324,"对不起，该页面异常，请联系管理员")} />
    );
  }
}

Repeat = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Repeat);

export default Repeat
